package com.spzx.user.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.user.mapper.RegionMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.UserAddressMapper;
import com.spzx.user.api.domain.UserAddress;
import com.spzx.user.service.IUserAddressService;

/**
 * 用户地址Service业务层处理
 *
 * @author atguigu
 * @date 2024-07-03
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;

    @Resource
    RegionMapper regionMapper;

    /**
     * 查询用户地址列表
     *
     * @param userAddress 用户地址
     * @return 用户地址
     */
    @Override
    public List<UserAddress> selectUserAddressList(UserAddress userAddress) {
        return userAddressMapper.selectUserAddressList(userAddress);
    }

    @Override
    public boolean saveAddress(UserAddress userAddress) {
        //新增地址时，如果本次新增的是默认地址 先将之前的默认地址改为非默认( 前端默认getIsDefault为1 时 为默认地址 )
        Long userId = SecurityUtils.getUserId();
        if (userAddress.getIsDefault().longValue() == 1l) {
            this.update(Wrappers.lambdaUpdate(UserAddress.class).eq(UserAddress::getUserId, userId)
                    .eq(UserAddress::getIsDefault, 1)
                    .set(UserAddress::getIsDefault, 0));
        }
        //绑定用户和收货地址
        userAddress.setUserId(userId);
        //拼接完整地址:
        //自定义mapper方法，使用三级区域的code值获取 省市区名称 字符串

        String regionNames = regionMapper.selectLevel123NameByCode(userAddress.getDistrictCode());
        String fullNames = regionNames + " " + userAddress.getAddress();
        userAddress.setFullAddress(fullNames);
        this.save(userAddress);

        return true;
    }

}
